import Ball from '../sprite/ball.js'

export default class MultiCurve {
  constructor() {
    this.canvas = wx.createCanvas()
    this.context = this.canvas.getContext('2d')
    this.sprites = []
    this.loop = this.drawFrame.bind(this)
    this.touchHandler = this.touchEventHandler.bind(this)
    wx.onTouchMove(this.touchHandler)

    this.context.lineWidth = 2
    this.context.strokeStyle = "#00FF00"

    let points = [],
      numPoints = 7

    // array of random point objects
    for (let i = 0; i < numPoints; ++i) {
      points.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
      })
    }

    // find the first midpoint and move to it
    let ctrlPoint1 = {}
    ctrlPoint1.x = (points[0].x + points[numPoints - 1].x) / 2
    ctrlPoint1.y = (points[0].y + points[numPoints - 1].y) / 2
    this.context.beginPath()
    this.context.moveTo(ctrlPoint1.x, ctrlPoint1.y)

    // and loop through each successive pair
    let i = 0
    for (; i < numPoints - 1; ++i) {
      let ctrlPoint = {}
      ctrlPoint.x = points[i].x + points[i + 1].x / 2
      ctrlPoint.y = points[i].y + points[i + 1].y / 2
      this.context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint.x, ctrlPoint.y)
    }
    this.context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint1.x, ctrlPoint1.y)
    this.context.stroke()
  }

  touchEventHandler(e) {

  }

  addChild(sprite) {
    if (sprite) {
      this.sprites.push(sprite)
    }
  }

  drawFrame() {
    requestAnimationFrame(this.loop)
    // this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
    for (let sprite of this.sprites) {
      sprite.draw(this.context)
    }
  }
}